import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:qianyi/controller/webSockerController.dart';
import 'package:qianyi/pages/home/community/index.dart';
import 'package:qianyi/pages/home/message/index.dart';
import 'package:qianyi/pages/home/mine/index.dart';
import 'package:qianyi/pages/home/publish/index.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:get/get.dart';
import 'package:badges/badges.dart' as badges;

import 'community/page_view/found/index.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin{
  int curPage = 0; // 初始化为1，因为首页已经删除
  final PageController _pageController = PageController(initialPage: 0);
  TokenController _tokenController = Get.find<TokenController>();
  DateTime? _lastBackPressed;
  WebSocketController webSocketController = Get.find();
  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    webSocketController.onInit();
    super.initState();

    Future.delayed(Duration.zero, () {
      if (_tokenController.tokenString.isEmpty) {
        Get.toNamed('/login/verify-code');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
      body: WillPopScope(
        onWillPop: () async {
          final now = DateTime.now();
          final backButtonPressThreshold = 2; // 两次返回键点击的时间阈值（秒）
          final backButtonDoublePressDelay = 2; // 延迟时间（秒）



          if (_lastBackPressed == null ||
              now.difference(_lastBackPressed!) > Duration(seconds: backButtonPressThreshold)) {
            // 如果两次点击间隔超过阈值，则更新_lastBackPressed为当前时间
            _lastBackPressed = now;
            // 显示提示信息
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('再按一次返回键退出应用')),
            );
            // 返回false，表示不执行返回操作
            return false;
          } else {
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            return true;

          }

          // 如果两次点击间隔小于阈值，则退出应用
        },
        child:  PageView(
          controller: _pageController,
          physics: const NeverScrollableScrollPhysics(),
          children:  [
            // 移除了 PageViewIndex()
            PageViewCommunity(),
            SearchPage(),
            Publish(),

            PageViewMessage(),
            PageViewMine(),
          ],
        ),
      )
      ,

      resizeToAvoidBottomInset: true,
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: BottomAppBar(

        height: 46,
        shape: const CircularNotchedRectangle(),
        child:  // 取消内边距
        Row(

          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center, // 设置垂直居中

          children: [
            // 移除了首页对应的 barItem()

            barItem(curPage == 0, 0, icon: Icons.access_alarm, text: "首页"),
            barItem(curPage == 1, 1, icon: Icons.access_alarm, text: "搜索"),
            barItem(curPage == 2, 2, icon: Icons.access_alarm, text: "发布"),
            // const SizedBox(
            //   width: 48,
            // ),
            barItem(curPage == 3, 3, icon: Icons.message_sharp, text: "消息"),
            barItem(curPage == 4, 4, icon: Icons.person, text: "我的"),
          ],
        ),

      ),
    )
      ;
  }

  Container barItem(
      bool active,
      int initPage, {
        required IconData icon,
        required String text,
      }) {


    return Container(


      child: GestureDetector(

          onTap: (){
            setState(() {
              curPage = initPage;
              _pageController.jumpToPage(curPage);
            });
          },
          child:text=="发布"?Row(children: [Padding(padding: EdgeInsets.only(bottom: 0),child: Icon(CupertinoIcons.add_circled_solid,size: 30,color: WcaoTheme.primary,)),],):
          text=="消息"?
          Obx(() => webSocketController.messageValue>0?
          badges.Badge(
            //    样式
            badgeStyle: badges.BadgeStyle(
                badgeColor: WcaoTheme.primary,
                shape: badges.BadgeShape.circle, // 形状
                borderRadius: BorderRadius.circular(10)),

            badgeContent: Text('${webSocketController.messageValue!}',style: TextStyle(fontSize:13,color: Colors.orange),)
            ,
            child: Text("消息", style: TextStyle(
              fontSize: 20,
              fontWeight: active ? FontWeight.w500 : FontWeight.w300,
              color: active ? WcaoTheme.indexBootBarActColor : WcaoTheme.indexBootBarColor,
            )),
          )
              :badges.Badge(
            //    样式
            badgeStyle: badges.BadgeStyle(
                badgeColor: WcaoTheme.primary,
                shape: badges.BadgeShape.circle, // 形状
                borderRadius: BorderRadius.circular(10),
                padding : const EdgeInsets.all(0)
            ),


            child: Text("消息", style: TextStyle(
              fontSize: 20,
              fontWeight: active ? FontWeight.w500 : FontWeight.w300,
              color: active ? WcaoTheme.indexBootBarActColor : WcaoTheme.indexBootBarColor,
            )),
          )


          ):
          Text(
          text,

        style: TextStyle(
          fontSize: 20,
          fontWeight: active ? FontWeight.w500 : FontWeight.w300,
          color: active ? WcaoTheme.indexBootBarActColor : WcaoTheme.indexBootBarColor,
        ),
      )

      ),
    );
  }

  @override
  void detach() {
    // TODO: implement detach
  }



  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}


